<template>
  <div class="budget">
    <el-card>
      <CommonForm v-if="isRouterAlive" />
    </el-card>
    <el-card>
      <NavTab />
    </el-card>
    <el-card>
      <div class="budget-content">
        <el-form ref="form" :inline="true" label-width="130px" :model="form">
          <el-form-item label="设备编号：">
            <el-input v-model="form.EQUIPMENT_ID" />
          </el-form-item>
          <el-form-item label="设备类型：">
            <el-cascader v-model="form.TYPE_ID" clearable :options="typeOptions" placeholder="请选择" :props="props" :show-all-levels="false" />
          </el-form-item>
          <el-form-item>
            <el-button @click="reset">
              <vui-icon icon="refresh-line" />
              重置
            </el-button>
            <el-button type="primary" @click="search">
              <vui-icon icon="search-line" />
              查询
            </el-button>
          </el-form-item>
          <el-form-item>
            <div class="btns">
              <el-button :disabled="list.length == 0 ? true : releaseAfter" style="margin-left: 10px" type="primary" @click="dataRelease">
                <vui-icon icon="save-line" />
                发布数据
              </el-button>
              <el-button type="primary" @click="newUpload">
                <vui-icon icon="upload-line" />
                上传新数据
              </el-button>
              <el-button @click="toAccessory">
                <vui-icon icon="history-line" />
                附件记录
              </el-button>
            </div>
          </el-form-item>
        </el-form>
        <el-table border :data="list" highlight-current-row :max-height="500">
          <el-table-column label="设备编号" prop="EQUIPMENT_ID" />
          <el-table-column label="设备类型" width="200">
            <template #default="{ row }">
              <el-cascader
                v-model="row.EQUIPMENT_TYPE"
                clearable
                :disabled="releaseAfter"
                :options="typeOptions"
                placeholder="请选择"
                :props="props"
                :show-all-levels="false"
              />
            </template>
          </el-table-column>
          <el-table-column label="数量" width="170">
            <template #default="{ row }">
              <el-input-number v-model="row.QTY" controls-position="right" :disabled="releaseAfter" :max="9999" :min="1" size="mini" />
            </template>
          </el-table-column>
          <el-table-column label="单位" prop="UNITS" />
          <el-table-column label="是否利旧">
            <template #default="{ row }">
              <el-switch v-model="row.OLD_WHETHER" active-value="Y" :disabled="releaseAfter" inactive-value="N" />
            </template>
          </el-table-column>
          <el-table-column label="长(固定端)(mm)" width="150">
            <template #default="{ row }">
              <el-input v-model="row.LENGTH" :disabled="releaseAfter" oninput="value=value.replace(/[^0-9.]/g,'')" />
            </template>
          </el-table-column>
          <el-table-column label="有效宽度（mm）" width="150">
            <template #default="{ row }">
              <el-input v-model="row.WIDTH" :disabled="releaseAfter" oninput="value=value.replace(/[^0-9.]/g,'')" />
            </template>
          </el-table-column>
          <el-table-column label="高(mm）" width="150">
            <template #default="{ row }">
              <el-input v-model="row.HEIGHT" :disabled="releaseAfter" oninput="value=value.replace(/[^0-9.]/g,'')" />
            </template>
          </el-table-column>
          <el-table-column label="爬坡带直段（mm）" width="150">
            <template #default="{ row }">
              <el-input v-model="row.CLIMB_LENGTH" :disabled="releaseAfter" oninput="value=value.replace(/[^0-9.]/g,'')" />
            </template>
          </el-table-column>
          <el-table-column label="分拣流向" width="150">
            <template #default="{ row }">
              <el-input v-model="row.SORTING_FLOW" :disabled="releaseAfter" oninput="value=value.replace(/[^0-9.]/g,'')" />
            </template>
          </el-table-column>
          <el-table-column label="伸缩长度（mm）" width="150">
            <template #default="{ row }">
              <el-input v-model="row.FLEX_LENGTH" :disabled="releaseAfter" oninput="value=value.replace(/[^0-9.]/g,'')" />
            </template>
          </el-table-column>
          <el-table-column label="线速度（m/min）" width="150">
            <template #default="{ row }">
              <el-input v-model="row.LINEAR_VELOCITY" :disabled="releaseAfter" />
            </template>
          </el-table-column>
          <el-table-column label="电机功率（KW）" width="150">
            <template #default="{ row }">
              <el-input v-model="row.MOTOR_POWER" :disabled="releaseAfter" oninput="value=value.replace(/[^0-9.]/g,'')" />
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" width="180">
            <template #default="{ row }">
              <el-button :disabled="releaseAfter" type="primary" @click="save(row)">
                <vui-icon icon="save-line" type="primary" />
                保存
              </el-button>
              <el-button :disabled="releaseAfter" type="primary" @click="copy(row)">
                <vui-icon icon="file-copy-line" type="primary" />
                复制
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>
    <el-dialog v-model="uploadVisible" title="附件上传" width="80%" @close="cancel">
      <upload-dialog v-if="uploadVisible" @cancel="cancel" @success="dialogSuccess" />
    </el-dialog>
    <el-dialog v-model="copyVisible" title="复制列" width="50%">
      <el-table border :data="copyList" style="width: 100%" @selection-change="handleSelectionChange">
        <el-table-column label="复制列" type="selection" width="55" />
        <el-table-column label="列名" prop="name" />
      </el-table>
      <div class="column-btn">
        <el-button @click="copyVisible = false">取消</el-button>
        <el-button type="primary" @click="confirm">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
  import CommonForm from '@bqms/components/ComTable.vue'
  import UploadDialog from '../../components/uploadDialog.vue'
  import requestMethod from '../../common/requestMethod'
  import publicFn from '../../common/requestCommon'
  import NavTab from '../../components/NavTab.vue'
  const dataItem = ['EQUIPMENT_TYPE', 'QTY', 'OLD_WHETHER', 'LENGTH', 'WIDTH', 'HEIGHT', 'LINEAR_VELOCITY', 'MOTOR_POWER']
  export default {
    name: 'BudgetDetails',
    components: {
      CommonForm,
      UploadDialog,
      NavTab,
    },
    data() {
      return {
        isRouterAlive: true,
        copyVisible: false,
        copyList: [
          { name: '设备类型', key: 'EQUIPMENT_TYPE' },
          { name: '数量', key: 'QTY' },
          { name: '是否利旧', key: 'OLD_WHETHER' },
          { name: '长', key: 'LENGTH' },
          { name: '宽', key: 'WIDTH' },
          { name: '高', key: 'HEIGHT' },
          { name: '爬坡带直段', key: 'CLIMB_LENGTH' },
          { name: '分拣流向', key: 'SORTING_FLOW' },
          { name: '伸缩长度', key: 'FLEX_LENGTH' },
          { name: '线速度', key: 'LINEAR_VELOCITY' },
          { name: '电机功率', key: 'MOTOR_POWER' },
        ],
        releaseAfter: false,
        uploadVisible: false,
        form: {},
        list: [],
        typeOptions: [],
        srcArr: [],
        props: {
          emitPath: false, //绑定的内容只获取最后一级的value值。
        },
        formEnd: {},
        errorData: {},
        uploadList: [],
        abnormal: false,
        multipleSelection: [],
        aloneColumn: {},
      }
    },
    created() {
      this.getTypeList()
    },
    activated() {
      this.list = []
      this.form = {}
      this.isRouterAlive = false
      this.$nextTick(() => (this.isRouterAlive = true))
      this.getTableHeader()
    },
    methods: {
      dialogSuccess() {
        this.releaseAfter = false
      },
      toAccessory() {
        this.$router.push('/1305')
      },
      async getTableHeader() {
        let res = await publicFn(requestMethod.GET_TABLE_HEADER, {
          '#LIMIT#': 1,
          '#PAGE_SIZE#': 99999,
          DOCNO: this.$store.getters['bqmsData/budgetSheetNum'], //单号
        })
        if (res.code == '00000') {
          if (res.data[requestMethod.GET_TABLE_HEADER].data[0].DOC_STATUS == '单据创建') {
            this.releaseAfter = false
          } else {
            this.releaseAfter = true
          }
          this.$pub(`topFormData`, true)
        }
      },
      async confirm() {
        if (this.multipleSelection.length == 0) return this.$message({ type: 'error', message: '请选择列行' })
        let list = this.multipleSelection.map((el) => el.key)
        let obj = {}
        list.forEach((row) => {
          obj[row] = this.aloneColumn[row]
        })
        let res = await publicFn(requestMethod.COPY_UPDATE, { DOCNO: this.aloneColumn.DOCNO, ...obj })
        if (res.code === '00000') {
          this.$message({
            type: 'success',
            message: '复制成功',
          })
          this.copyVisible = false
          this.getDetailsList()
        } else {
          this.$message({
            type: 'info',
            message: res.msg,
          })
        }
      },
      handleSelectionChange(val) {
        this.multipleSelection = val
      },
      copy(row) {
        this.aloneColumn = row
        this.copyVisible = true
        // this.multipleSelection = []
      },
      async save(row) {
        let msgHint = false
        let list = ['EQUIPMENT_TYPE', 'QTY', 'OLD_WHETHER', 'LENGTH', 'WIDTH', 'HEIGHT', 'LINEAR_VELOCITY', 'MOTOR_POWER']
        list.forEach((key) => {
          if (row[key] === '') {
            msgHint = true
          }
        })
        if (msgHint) return this.$message({ type: 'warning', message: '请将此行除爬坡带直段、分拣流向、伸缩长度的内容填写完整' })
        let res = await publicFn(requestMethod.DETAILS_UPDATE, row)
        if (res.code === '00000') {
          this.$message({
            type: 'success',
            message: '保存成功',
          })
        } else {
          this.$message({
            type: 'info',
            message: res.msg,
          })
        }
      },
      reset() {
        this.form = {}
        this.search()
      },
      search() {
        this.getDetailsList()
      },
      dataRelease() {
        this.$confirm('请再次确认是否要发布数据，一旦发布，数据将不可再更改？若要重新更改，需要重新上传新版本附件?', '发布数据', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
          .then(async () => {
            let switchOpen = false
            this.list.forEach((row) => {
              dataItem.forEach((item) => {
                if (!row[item]) switchOpen = true
              })
            })
            if (switchOpen) {
              this.$message({
                type: 'warning',
                message: '请输入完整信息再发布!!!',
              })
            } else {
              let res = await publicFn(requestMethod.DATA_RELEASE, {
                TYPE: 'BASIC_DATA_ISSUE',
                DOCNO: this.$store.getters['bqmsData/budgetSheetNum'],
              })
              if (res.code === '00000') {
                this.$message({
                  type: 'success',
                  message: '发布成功!',
                })
                this.releaseAfter = true
                this.getDetailsList()
              } else {
                this.$message({
                  type: 'info',
                  message: res.msg,
                })
              }
            }
          })
          .catch((e) => {
            console.log(e)
          })
      },
      newUpload() {
        this.uploadVisible = true
      },
      cancel() {
        this.uploadVisible = false
        this.getDetailsList()
      },
      async getDetailsList() {
        let res = await publicFn(requestMethod.DETAILS_GET, {
          '#LIMIT#': 1,
          '#PAGE_SIZE#': 99999,
          ...this.form,
          OUT_SOURCE: 'N',
          DOCNO: this.$store.getters['bqmsData/budgetSheetNum'],
          // VERSION: this.$store.getters['bqmsData/HeaderTable'].VERSION,
        })
        if (res.code === '00000') {
          this.list = res.data
        } else {
          this.$message({
            type: 'info',
            message: res.msg,
          })
        }
      },
      async getTypeList() {
        let res = await publicFn(requestMethod.TYPE_LIST, { '#LIMIT#': 1, '#PAGE_SIZE#': 99999 })
        if (res.code === '00000') {
          this.srcArr = res.data[requestMethod.TYPE_LIST].data
          res.data[requestMethod.TYPE_LIST].data.forEach((item) => {
            if (item.PARAENT_TYPE_ID == 0) {
              this.typeOptions.push({
                parentId: item.PARAENT_TYPE_ID,
                value: item.TYPE_ID,
                label: item.TYPE_NAME,
                children: [],
              })
            }
          })
          this.typeOptions.forEach((it) => {
            it.children = this.getChildren(it.value, this.srcArr)
          })
        } else {
          this.$message({
            type: 'info',
            message: res.msg,
          })
        }
      },
      // 处理级联--递归
      getChildren(tId, srcArr) {
        let children = []
        srcArr.forEach((item) => {
          if (item.PARAENT_TYPE_ID == tId) {
            children.push({
              parentId: item.PARAENT_TYPE_ID,
              value: item.TYPE_ID,
              label: item.TYPE_NAME,
              children: [],
            })
          }
        })
        if (children.length == 0) {
          return null
        }
        children.forEach((item) => {
          item.children = this.getChildren(item.value, this.srcArr)
        })
        return children
      },
    },
  }
</script>
<style lang="scss" scoped>
  .budget {
    width: calc(100% - 40px);
    padding: 20px;
    .btns {
      display: flex;
      flex-direction: row-reverse;
    }
  }
  .column-btn {
    padding: 15px;
    text-align: center;
    box-sizing: border-box;
  }
</style>
